package com.dissertation.service.impl;

import com.dissertation.model.Tag;
import com.dissertation.pojo.Message;
import com.dissertation.respository.TagRepository;
import com.dissertation.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;

@Service
public class CheckTagImpl implements ITagService {

    @Autowired
    MongoTemplate template;

    @Autowired
    TagRepository tagRepository;

    /**
     * 当tag更新的时候更新关联asset
     */
    private void updateArray( String old, String newStr ) {
        Query query = Query.query( where( "tags" ).is( old ));
        Update update = Update.update( "tags.$", newStr );
        template.updateMulti( query, update, "assets" );
    }

    @Override
    public Message save( Tag tag ) {
        List<Tag> tags = tagRepository.findByUniqueName( tag.getUniqueName() );
        if ( tags.size() != 0 ) {
            return Message.createErr( "对不起，已经存在同名标签" );
        }
        return Message.createSuc( tagRepository.save( tag ).getId() );
    }

    @Override
    public Message update( Tag tag ) {
        if ( tag.getId() == null ) {
            return Message.createErr( "对不起，更新请传入id" );
        }
        Tag tagOld = tagRepository.findOne( tag.getId() );
        if ( tagOld == null ) {
            return Message.createErr( "对不起，数据库不存在id=" + tag.getId() + "的数据" );
        }
        Message resp = save( tag );

        if ( resp.isErr() ) {
            updateArray( tagOld.getUniqueName(), tag.getUniqueName() );
        }
        return resp;
    }

    @Override
    public Message findAll() {
        Query query = new Query().with( new Sort( Sort.Direction.ASC, "status" ) );
        return Message.createSuc( template.find( query, Tag.class ) );
    }

    @Override
    public Message delete(Tag tag) {
        if(tag.getId()==null){
            return Message.createErr("对不起，请传入id");
        }
        Tag tag1 = tagRepository.findOne(tag.getId());
        if(tag1==null){
            return Message.createErr("对不起，数据库不存在id=" + tag.getId() + "的数据");
        }
        tagRepository.delete(tag.getId());
        return Message.createSuc("删除成功！");
    }
}
